package com.xy.job.admin.service

import com.xy.job.admin.api.request.JobGroupAddParam
import com.xy.job.admin.api.request.JobGroupQueryParam
import com.xy.job.admin.domain.JobGroup
import com.xy.job.admin.repository.JobGroupRepository
import com.xy.job.core.exception.BizException
import org.springframework.data.domain.*
import org.springframework.stereotype.Service

@Service
class JobGroupService(
    private var jobGroupRepository: JobGroupRepository,
) {

    fun list(param: JobGroupQueryParam): Page<JobGroup> {
        val pageable: Pageable = PageRequest.of(
            param.pageNo - 1, param.pageSize, Sort.by(JobGroup::id.name).descending()
        )
        val jobGroup = JobGroup().apply {
            this.groupCode = param.groupCode
            this.groupName = param.groupName
        }
        val matcher = ExampleMatcher.matchingAll()
            .withMatcher(JobGroup::groupCode.name, ExampleMatcher.GenericPropertyMatchers.contains())
            .withMatcher(JobGroup::groupName.name, ExampleMatcher.GenericPropertyMatchers.contains())
        val example = Example.of(jobGroup, matcher)
        return jobGroupRepository.findAll(example, pageable)
    }

    fun add(param: JobGroupAddParam): JobGroup {
        if (jobGroupRepository.findByGroupCode(param.groupCode) != null) {
            throw BizException("exist executor [${param.groupCode}]")
        }
        val jobGroup = JobGroup().apply {
            this.groupCode = param.groupCode
            this.groupName = param.groupName
        }
        jobGroupRepository.save(jobGroup)
        return jobGroup
    }

}